/**
*  订单总额  =  微信卡券抵扣金额  +  一卡通支付金额  
*  或
*  订单总额  =  微信卡券优惠金额  +  微信支付金额 
*  或
*  订单总额  =  微信支付金额
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var when = require("mlib/util/when");
var ajax = require("mlib/io/ajax");
var lazyload = require("mlib/dom/lazyload");
var closest = require("mlib/dom/closest");

var round = require("../plugin/util/round");
var date = require("../plugin/util/date");

var Validator = require("../plugin/util/validator");
var animationEnd = require("../plugin/animation/animationEnd");
var currency = require("../plugin/util/currency");
var quantity = require("../plugin/util/up-down");
var prefix = require("../plugin/transform/prefix");
var calendar = require("../plugin/date/calendar"); // 日历函数

var Dialog = require("../layer/dialog");
var Alert = require("../layer/weuialert");
var weuiConfirm = require('../layer/weuiconfirm');


var touch = require("mlib/evt/touch");

var layerRender = require("./layer.ejs");
var listRender = require("./couponlist.ejs");
var cardRender = require("./cardlist.ejs");
var detailRender = require("./detail.ejs");




module.exports = function(node, opts) {

    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	
    var navIndex=0; 
	var m_quantity = null;
	
	var m_total_price = 0; // 商品总金额
	var m_pay_price = 0; // 商品实际支付金额
	var m_coupon_price = 0; // 商品优惠金额
	var m_coupon_maxprice = 0; // 记录优惠券的金额

    var exprestr = null ; // 优惠券计算方式
	
	var store_mopon = []; // 存储所有优惠券

	var store_moponids = []; // 存储所有优惠券关联

	var cur_coupon = null; // 记录当前选中的优惠券

	var m_couponobj = null;// 记录当前选中的优惠券对象
	
	var m_validator = null ;
	var detail_content = null ;
	var expreResult = null;
	var m_gb = null;
	var m_submit_content = null;
	var m_temp_data = null;


	var m_navbar = null;
	var m_tab_navs = null;
	var m_tab_contents = null;
	var m_tab_container = null;
	var m_cardnodes = null;
	var m_couponodes = null;
    var fc_nodes = null; //满减优惠券节点
 
	var m_scheduled = null;


   
	var isPassed = false; // 手机身份证号码验证是否通过
	var m_today = null ;

    //-------------事件响应声明---------------
	//alert("sss");
    var evtFuncs = {
        	preferential:function(evt){ // 选择优惠券
				var target=closest(evt.target,".coupon-item",true);
				if(target.classList.contains("disabled")){
                     return;
				}
				m_couponodes.forEach(function(item){
					if(item==target){
						item.classList.toggle("coupon-item-checked");						
						if(item.classList.contains("coupon-item-checked")){
							cur_coupon = item.dataset.cardid;
							var reckonprice = eval(m_total_price+item.dataset.reckon);// 运行计算公式
							

						}else{
							cur_coupon = null; 
							m_coupon_maxprice = 0;
						}					
							
						custFuncs.updatePrice();
					}else{
						item.classList.remove("coupon-item-checked");	
					}
				});	
        	}, 
			bindQ:function(result){ // 修改数量                 
				 var obj=result.data,
					 input=obj.input,
					 theval =input.value;
					 m_total_price = parseInt(theval) * parseFloat(data.goodsBase.price);
					custFuncs.updatePrice();	
			},
			 validatorForm:function(evt){
				 m_validator.validate({type:evt.type,node:evt.target});
			 },
			 showDetail:function(){					 
				if(m_tab_navs){
					nodeList.detailayer.style.display = "block"; 
					nodeList.detailmask.style.opacity =".7";
					m_tab_container.classList.add("slidein")
					animationEnd(m_tab_container, "AnimationEnd", function () {
						m_tab_container.classList.remove("slidein");
					}, false);	
				}else{
					document.body.classList.add('modal-open');
					ajax({ 
						url: "index.php?r=goods/goodsdetail&id="+ data.id+"&ocid="+ data.ocid,
						onSuccess: function(result) {
							detail_content = detailRender({"arrpos":custFuncs.getPos(2).attrpos,"detailh":custFuncs.getPos(2).detailh,"bookingnotice":result.bookingnotice,"description":result.description});
							nodeList.detailayer.insertAdjacentHTML("beforeend",detail_content);
							
							m_navbar = nodeList.detailayer.querySelector(".swiper-scrollbar-drag");
							m_tab_container = nodeList.detailayer.querySelector(".tab-container");
							m_tab_navs = [].slice.call(nodeList.detailayer.querySelectorAll(".nav-item"));
							m_tab_contents = [].slice.call(nodeList.detailayer.querySelectorAll(".content-item"));		
                            nodeList.detailayer.style.display = "block"; 	
							nodeList.detailmask.style.opacity =".7";
							m_tab_container.classList.add("slidein")
							animationEnd(m_tab_container, "AnimationEnd", function () {
								m_tab_container.classList.remove("slidein");
							}, false);	
						},
						onError: function(xmlHttp) {
	                        that.unLock();
	                    }
					});
				}
			 },
			 hideDetail:function(){
				document.body.classList.remove('modal-open');
				nodeList.detailmask.style.opacity ="0";
				m_tab_container.classList.add("slideout")
				animationEnd(m_tab_container, "AnimationEnd", function () {
					m_tab_container.classList.remove("slideout")
					nodeList.detailayer.style.display ="none";
				}, false);	
			 },
			submitOrder:function(){
				evtFuncs.validatorForm({type:"submit",node:null})
				if(isPassed){
                    m_temp_data = {};					
					var params={},inputs = [].slice.call(nodeList.append.querySelectorAll("input.quantity")),datalist=[];
					inputs.forEach(function(item,index){
						var itemobj = item.dataset;
						itemobj.number = item.value;
						datalist.push(itemobj);
					});
					if(cur_coupon){
						m_temp_data["card"] = [{"cardid":m_couponobj.cardid,"cardcode":m_couponobj.code.codeId,"couponprice":currency(m_coupon_price),"coupontitle":m_couponobj.title}];						
					}else{
						m_temp_data["card"] = [];
					}

					params["card"] = JSON.stringify(m_temp_data["card"]);
					params["list"] =JSON.stringify(datalist);
					
					params["totalprice"] = m_total_price;
					
					params["mobile"] = nodeList.mobile.value;					
					if(nodeList.idcard){
						params["idcard"] =nodeList.idcard.value||"";
					}else{
						params["idcard"] = '';
					}
					if(data.goodsBase.tcid){
						params["tcid"] = data.goodsBase.tcid;
					}
					m_temp_data["goodsBase"] =data.goodsBase;

					m_temp_data["weeks"] =data.weeks;
					if(data.goodsBase.date){
						m_temp_data["date"] =data.goodsBase.date;
						params["scheduled_time"] =data.goodsBase.date;
					}else{
						m_temp_data["date"] = m_today;
						params["scheduled_time"] = m_today;
					}
					
					m_temp_data["week"] =data.week;
					m_temp_data["msg"] =data.msg;
					m_temp_data["idcard"] = params["idcard"];
					m_temp_data["list"] = datalist;
					m_temp_data["mobile"] = params["mobile"];					

                    params["ocid"] = data.ocid;
                    params["tid"] = data.tid;

					
                    
	                if(that.isLock()) {
	                    return;
	                }
	                that.lock();
					ajax({ 
						url: "index.php?r=scheduled/scheduled&ocid="+ data.ocid,
						data: params, 
						method: "post",
						onSuccess: function(result) {	
                            that.unLock();	
	
							m_submit_content =  layerRender(m_temp_data);	
							
							Dialog({
								title:"订单确认",
								content:m_submit_content,
								operates:[{name:"pay",cls:"full-btn",text:"<span>立即支付</span> <span>&yen;"+currency(m_pay_price)+"</span>",fn:function(){
										if(that.isLock()) {
						                    return;
						                }
						                that.lock();
										ajax({
											url: "index.php?r=scheduled/order&ocid="+ data.ocid,
											data: result,
											method: "post",
											onSuccess: function(res) {												    		
												if(res.status==1){
													var baseurl = '/index.php?r=scheduled/pay&orderid='+res.data.orderNo+'&ocid='+data.ocid;
													//微信支付
													//泰久卡支付
													//微信卡券全额支付
													if(m_pay_price==0 && cur_coupon){
														location.href=baseurl+'&type=WECHAT_CARD';
													}else{
														location.href=baseurl+'&type=WECHAT_JS';
													}
													//location.href=res.url
												}else{
													that.unLock();	
													Alert(res.msg);
												} 

											},
											onError: function(xmlHttp) {
						                        that.unLock();
						                    }
										});
								}}]
							}).init();
							
						},
						onError: function(xmlHttp) {
	                        that.unLock();
	                    }
					});
				}
			},
			initDetail:function(evt){
               var target= closest(evt.target,".nav-item",true),navIndex = parseInt(target.dataset.index);
			   
				m_tab_navs.forEach(function(item,index){						
					if(navIndex==index){
						item.classList.add("active-nav");
						m_tab_contents[index].style.display = "block";
						m_tab_contents[index].scrollTop=0;
						custFuncs.updateBarPosition(index);
						
					}else{
						item.classList.remove("active-nav");
						m_tab_contents[index].style.display = "none";
					}
				});
			}
    }

    //-------------子模块实例化---------------
    var initMod = function() {
		m_today = new Date().getFullYear() +"-"+ (new Date().getMonth()+1)+"-" + new Date().getDate();
		m_gb = pageConfig.modules.goodsBase;
		m_quantity = quantity(nodeList.append,{});
		m_scheduled = calendar({"scheduled":true});
		if(Array.isArray(m_gb)){	
			m_scheduled.init(data);		
			m_scheduled.getCalendar({
				"year":new Date().getFullYear(),
				"month":new Date().getMonth(),
				"gid":data.id,
				"elemjson":JSON.stringify({"title":data.title,"id":data.id,"thumb":""}),
				"callback":function(res){
					document.querySelector(".pbd").style.visibility ='visible';
					document.querySelector(".opt-full-btn").style.visibility ='visible';
					nodeList.datepicker.style.display = "block";
					nodeList.mask.style.opacity ="1";
					nodeList.datebox.classList.add("slidein")
					animationEnd(nodeList.datebox, "AnimationEnd", function () {
						nodeList.datebox.classList.remove("slidein");
					}, false);	
				}
			});
		}else{
			if(m_gb.dateType==2){
				Alert('您购买的商品有效期为<div class="f-green">'+m_gb.effectStart.replace(/\s\d+:\d+:\d+/,"")+"至"+m_gb.effectEnd.replace(/\s\d+:\d+:\d+/,"")+"</div><div>详细规则请查看预定须知</div>");
			}else if(m_gb.dateType==3){	
				if(m_gb.effectStart>0){
					if(m_gb.effectType==1){
						Alert('您购买的商品购买后将在<div class="f-green">'+m_gb.effectStart+"天后生效</div><div>详细规则请查看预定须知</div>");
					}else{
						Alert('您购买的商品购买后将在<div class="f-green">'+custFuncs.renderMinute(m_gb.effectStart)+"钟后生效</div><div>详细规则请查看预定须知</div>");
					}
				}else{
					//Alert('您购买的商品购买后将<div class="f-green">立即生效</div>');
				}
			}
			if(data.goodsBase.dateType=="1"){
				m_scheduled.init(data);	
			}
			m_total_price = parseFloat(m_gb.price)*parseInt(m_gb.singleBuyNum);// 初始化商品总价为商品单价
			m_pay_price = parseFloat(m_gb.price)*parseInt(m_gb.singleBuyNum);// 初始化支付总金额为商品单价
			
			

			var inforules =[{
				//name 字段
				name: 'mobile',
				display:"请输入您的手机号码|手机号码格式错误",
				// 验证条件
				rules: 'required|is_phone'
			}];
			if(data.goodsBase.needIdCard=="1"){
				inforules.push({
					//name 字段
					name: 'idcard',
					display:"请输入您的身份证号码|身份证号码格式错误",
					// 验证条件
					rules: 'required|is_idcard'
				});
			}
			m_validator = new Validator('info_form',inforules,function(obj,evt){
				isPassed =false;
				if(obj.errors.length>0){
					var firstObj = null;
					 obj.errors.forEach(function(item,index){
						 var itemEl = item.element;
						 if((evt.type==null || evt.type=='submit') && index==0){
							 firstObj = item;
						 }else{
							 if(evt.node==itemEl){
								 firstObj = item;
							 }
						 }

						 
						 if(itemEl.classList.contains("error")){
							 itemEl.classList.remove("error","shake");
						 }
						 
					 });
					 
					// 判断是否错误
					switch(evt.type){
						
						case "input":
							if(firstObj){
								var fev = firstObj.element.value;
								if(firstObj.rule=="is_phone" && fev.length>11){
									firstObj.element.classList.add("error");
								}else if(firstObj.rule=="is_idcard" && fev.length>18){
									firstObj.element.classList.add("error");
								}
							}                        
							break; 	
						case 'submit':						
						case "blur":
						case null:
							if(evt.type=='submit'){document.querySelector(".scheduled").scrollTop = 0;}
							if(firstObj){
								var cls = firstObj.rule =="required" ? "empty" : "error";
									firstObj.element.classList.add(cls,"shake");
									animationEnd(firstObj.element, 'AnimationEnd', function () {
										firstObj.element.classList.remove("shake");
									}, false);
							}
							break; 	
						
					}
					return ;
					 
				}
				isPassed =true;
			});

            // 先取优惠券，再取一卡通数据
            custFuncs.getCoupon();
			
		}
        var sharedata = {
            'title':data.title,
            'desc': data.description,
            'link':location.href,
            'imgUrl':data.imgsite+data.thumb,
            'type':'', 
            'dataUrl':'' 
		}

        wechat('open',sharedata).init();
    }

    //-------------绑定事件------------------
    var bindEvents = function() {
			m_quantity.bind("inputChange", evtFuncs.bindQ);
			touch.on(nodeList.submit,"tap",evtFuncs.submitOrder);
			touch.on(nodeList.detailayer,"tap",".nav-item",evtFuncs.initDetail);
			touch.on(nodeList.viewdetail,"tap",evtFuncs.showDetail);
			nodeList.mobile.addEventListener("blur", evtFuncs.validatorForm);			
			nodeList.mobile.addEventListener("input", evtFuncs.validatorForm);
			if(data.goodsBase.needIdCard=="1"){
				nodeList.idcard.addEventListener("blur", evtFuncs.validatorForm);
				nodeList.idcard.addEventListener("input", evtFuncs.validatorForm);
			}
			
			touch.on(nodeList.detailmask, 'tap', evtFuncs.hideDetail);




    }

    //-------------自定义函数----------------
    var custFuncs = {
		    renderMinute:function(minute){
				var hour,minu,timeStr=''; 
				if(minute>=1440){
					hour = hour=Math.floor((minute%1440)/60);
					minu = Math.floor(minute%60);
					timeStr += Math.floor(minute/1440) + "天";
					if(hour>0){
						timeStr += hour + "时";
					}
					if(minute>0){
						timeStr += minu + "分";
					}
				}else if(minute>=60){
					hour = Math.floor((minute%1440)/60);
					minu = Math.floor(minute%60);
					timeStr += hour + "时";
					if(minute>0){
						timeStr += minu + "分";
					}
				}else{
					if(minute>0){
						timeStr += minute + "分";
					}
				}
				return timeStr ;
			},
		   updateCoupon:function(money){
		   		fc_nodes  && fc_nodes.forEach(function(item,index){
                    if(m_total_price<parseFloat(item.dataset.money)){
                         item.classList.add("disabled");
                    }else{
                    	item.classList.remove("disabled");
                    }
		   		});
		   },
		   updateCouponNodes:function(){
		   	    fc_nodes = [];
		   		m_couponodes = [].slice.call(nodeList.couponlist.querySelectorAll(".coupon-item"));
		   		m_couponodes.forEach(function(item,index){
		   			if(item.hasAttribute("data-money")){
                       fc_nodes.push(item); 
		   			}
		   		});
		   },
           getCoupon:function(){// 获取优惠券，如果存在优惠券，默认选中第一张优惠券

				ajax({ 
					url: data.requestAPIUrl,
					data: {}, 
					method: "post",
					onSuccess: function(result) {	
						var couponmax =	document.querySelector(".couponmax");	
						if(result.status==1){                           
						   if(result.data.length>0){
							   result.data.forEach(function(item,index){
								   if(index==0){
									   	if(item.money==0){
										   cur_coupon = ""+item.cardId;
									   	}else if(m_total_price>round(item.money)){
											cur_coupon = ""+item.cardId;
									   	}
								   }
								   item.reckon = "-" + round(item.reduceCost);
								   item.amount = round(item.reduceCost);
								   store_mopon.push(item);
								   store_moponids.push(""+item.cardId);
							   });
								nodeList.couponlist.insertAdjacentHTML("beforeend",listRender({"couponlist":result.data}));	
								custFuncs.updateCouponNodes();	
								if(cur_coupon){
									m_couponodes[0].classList.add("coupon-item-checked");
								}
							   	touch.on(nodeList.couponlist, 'tap', ".coupon-item", evtFuncs.preferential);
						   }else{
							   couponmax.innerHTML = '<div class="no-coupon">无可使用优惠券</div>';							   							   
						   }	
							couponmax.style.display = "block";						   
						    custFuncs.updatePrice();	
						}else{
							couponmax.innerHTML = '<div class="no-coupon">无可使用优惠券</div>';	
							couponmax.style.display = "block";				
						}	

					},
					onError: function(xmlHttp) {

					}
				});
				//return defer.promise;
		   },
			updatePrice:function(){
				/*  
				* 四种情况支付
				* 1. 优惠券的抵扣金额大于等于订单总金额时，支持用券并抵扣
				* 2. 优惠券 + 一卡通支付(条件是优惠券金额+一卡通金额>=商品总额)
				* 3. 一卡通支付 (条件是一卡通金额>=商品总额)
				* 4. 微信 + 优惠券支付
				* 5. 微信支付
				*/				
                m_total_price = currency(m_total_price);
				if(cur_coupon){// 若存在已选中的优惠券  
					m_couponobj = store_mopon[store_moponids.indexOf(cur_coupon)];
					exprestr = m_total_price+m_couponobj.reckon;
					expreResult = eval(exprestr);
					m_pay_price=expreResult; // 支付金额
					m_coupon_price = currency(m_total_price-expreResult);// 优惠金额(优惠券优惠了多少)
					if(m_coupon_price-m_total_price>=0){//直接使用优惠券的抵扣金额					    
						m_coupon_price = m_total_price;
						m_coupon_maxprice = m_coupon_price;
						m_pay_price = 0;// 重置支付价格
					}else{//微信 + 优惠券支付
						m_pay_price = m_total_price-m_coupon_price;
					}
				}else{
					m_pay_price = m_total_price;
					m_coupon_price = 0;
				}

                m_pay_price = custFuncs.valBetween(m_pay_price,0,m_total_price);
				m_pay_price = currency(m_pay_price); 

				 custFuncs.updateCoupon();
				 nodeList.totalprice.setAttribute("data-price",""+m_pay_price);
				 nodeList.totalprice.innerHTML = ""+m_pay_price;
			},
			getPos:function(viewnum){
				var posarr=[],randomarr =custFuncs.range(viewnum),
				     doc=document.documentElement,
					 docH =doc.clientHeight,
					 docW =doc.clientWidth,
					 vrem = viewport.rem(),
					sw=(docW/vrem/viewnum),
					sh=(docH/vrem*0.6)-4.2,
					cpos=(sw-2.4)/2;
				randomarr.forEach(function(item,index){
					posarr.push(new Number(index*sw+cpos).toFixed(2));
				});

				return {
					"attrpos":posarr,
					"detailh":new Number(sh).toFixed(2)					
				};
			},
			range:function(start, stop, step) {
				if (stop == null) {
				  stop = start || 0;
				  start = 0;
				}
				step = step || 1;

				var length = Math.max(Math.ceil((stop - start) / step), 0);
				var range = Array(length);

				for (var idx = 0; idx < length; idx++, start += step) {
				  range[idx] = start;
				}

				return range;
			  },
			updateBarPosition:function(navIndex){
					var left = parseFloat(m_tab_navs[navIndex].getAttribute("data-pos"));
						m_navbar.style[prefix('transform')] = "translate3d("+ left + "rem,0,0)";
			},
		   valBetween:function(v, min, max){
			   return (Math.min(max, Math.max(min, v)));
		   }
   
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);

        // 子模块实例化
        initMod();

        // 绑定事件
        bindEvents();
    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};